package main

import (
	"bytes"
	jsoniter "github.com/json-iterator/go"
	"io/ioutil"
	"net/http"
	"strings"
)

var json = jsoniter.ConfigCompatibleWithStandardLibrary

type JSON struct {
	Access_token string `json:"access_token"`
}

type MESSAGES struct {
	Touser string `json:"touser"`
	Toparty string `json:"toparty"`
	Msgtype string `json:"msgtype"`
	Agentid int `json:"agentid"`
	Text struct {
		//Subject string `json:"subject"`
		Content string `json:"content"`
	} `json:"text"`
	Safe int `json:"safe"`
}

func Get_AccessToken(wechat *WechatServer) {
	gettoken_url := "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + wechat.ConfWechat.CorpId + "&corpsecret=" + wechat.ConfWechat.CorpSecret
	client := &http.Client{}
	req, err := client.Get(gettoken_url)
	if err != nil {
		sugarLogger.Errorf("%s 微信获取Token失败, err: %s", wechat.ConfWechat.CorpId, err)
		return
	}
	defer req.Body.Close()
	body, _ := ioutil.ReadAll(req.Body)
	idx := strings.Index(string(body), "ok")
	if idx == -1 {
		sugarLogger.Errorf("%s 微信获取Token失败, %s", wechat.ConfWechat.CorpId, string(body))
		return
	}
	var json_str JSON
	json.Unmarshal(body, &json_str)
	//fmt.Printf("\n%q",json_str.Access_token)
	wechat.ConfWechat.wechatToken = json_str.Access_token
	sugarLogger.Debugf("%s 微信Token获取成功: %s", wechat.ConfWechat.CorpId, wechat.ConfWechat.wechatToken)
}
func SendWechatMes(mes string) {
		for i, k := 0, len(FileNames.Wechat); i < k; i++ {
			SendMessage(FileNames.Wechat[i], setSedMsg(FileNames.Wechat[i], mes))
		}
}

func SendMessage(wechat WechatServer, sedMsg string) bool {
	send_url := "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + wechat.ConfWechat.wechatToken
	client := &http.Client{}
	req, err1 := http.NewRequest("POST", send_url, bytes.NewBuffer([]byte(sedMsg)))
	if err1 != nil {
		sugarLogger.Errorf("%s 微信http.NewRequest构造失败, err: %s", wechat.ConfWechat.CorpId, err1)
		return false
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("charset","UTF-8")
	resp, err := client.Do(req)
	if err != nil {
		sugarLogger.Errorf("%s 微信消息发送失败, %s  err: %s", wechat.ConfWechat.CorpId, sedMsg, err)
		return false
	}
	defer resp.Body.Close()
	return true
}

func setSedMsg(wechat WechatServer, mes string) string {
	return strings.Replace(messages(wechat.ConfWechat.ToUser, wechat.ConfWechat.ToParty, wechat.ConfWechat.AgentId, mes), "\\\\", "\\", -1)
}
func messages(touser string,toparty string,agentid int,content string) string {
	msg := MESSAGES{
		Touser: touser,
		Toparty: toparty,
		Msgtype: "text",
		Agentid: agentid,
		Safe: 0,
		Text: struct {
			Content string `json:"content"`
		}{Content: content},
	}
	sed_msg, _ := json.Marshal(msg)
	return string(sed_msg)
}
